package fitnesshub.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import fitnesshub.exception.AccountNotFoundException;
import fitnesshub.exception.PasswordErrorException;
import fitnesshub.exception.UsernameAlreadyExistsException;
import fitnesshub.mapper.MemberMapper;
import fitnesshub.pojo.dto.BuyMemberDTO;
import fitnesshub.pojo.dto.MemberLoginDTO;
import fitnesshub.pojo.dto.MemberRegisterDTO;
import fitnesshub.pojo.dto.MemberPageQueryDTO;
import fitnesshub.pojo.dto.ResetPasswordDTO;
import fitnesshub.pojo.entity.Member;
import fitnesshub.result.PageResult;
import fitnesshub.service.MemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;
    /**
     * 会员登录
     * @param memberLoginDTO
     * @return
     */
    @Override
    public Member login(MemberLoginDTO memberLoginDTO) {
        String username = memberLoginDTO.getUsername();
        String password = memberLoginDTO.getPassword();

        Member member = memberMapper.getByUsername(username);

        if (member == null) {
            throw new AccountNotFoundException("账号不存在");
        }
        // 加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(member.getPassword())) {
            throw new PasswordErrorException("密码错误");
        }

        return member;
    }

    /**
     * 获取会员信息
     *
     * @return
     */
    @Override
    public Member getMemberInfo(Integer memberId) {
        Member member = memberMapper.getById(memberId);
        member.setPassword("******");
        return member;
    }

    /**
     * 购买会员
     * @param buyMemberDTO
     * @return
     */
    @Override
    public void buyMember(BuyMemberDTO buyMemberDTO) {
        Member member = new Member();

        member.setMemberId(buyMemberDTO.getMemberId());
        member.setMemberType("会员");
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 转换 membershipStartDate
        LocalDateTime membershipStartDate = null;
        if (buyMemberDTO.getMembershipStartDate() != null && !buyMemberDTO.getMembershipStartDate().isEmpty()) {
            membershipStartDate = LocalDateTime.parse(buyMemberDTO.getMembershipStartDate(), formatter);
        }

        // 转换 membershipEndDate
        LocalDateTime membershipEndDate = null;
        if (buyMemberDTO.getMembershipEndDate() != null && !buyMemberDTO.getMembershipEndDate().isEmpty()) {
            membershipEndDate = LocalDateTime.parse(buyMemberDTO.getMembershipEndDate(), formatter);
        }

        // 设置转换后的日期到 member 对象
        member.setMembershipStartDate(membershipStartDate);
        member.setMembershipEndDate(membershipEndDate);

        member.setLastModifiedTime(LocalDateTime.now());

        // 购买的天数
        int days = buyMemberDTO.getDays();

        LocalDateTime now = LocalDateTime.now();
        if (membershipStartDate == null) {
            // 没有充值过会员
            member.setMembershipStartDate(now);
            member.setMembershipEndDate(now.plusDays(days));
        } else {
            // 充值过会员
            if (membershipEndDate != null && membershipEndDate.isAfter(now)) {
                // 会员还在有效期，续费
                member.setMembershipEndDate(membershipEndDate.plusDays(days));
            } else {
                // 会员已过期，重新开的会员
                member.setMembershipStartDate(now);
                member.setMembershipEndDate(now.plusDays(days));
            }
        }

        memberMapper.update(member);
    }

    /**
     * 更新用户信息
     * @param member
     * @return
     */
    @Override
    public void updateMemberInfo(Member member) {
        member.setLastModifiedTime(LocalDateTime.now());
        memberMapper.update(member);
    }

    /**
     * 用户重置密码
     * @param resetPasswordDTO
     * @return
     */
    @Override
    public void resetPassword(ResetPasswordDTO resetPasswordDTO) {
        String oldPassword = memberMapper.getPasswordById(resetPasswordDTO.getMemberId());
        String resetOldPassword = DigestUtils.md5DigestAsHex(resetPasswordDTO.getOldPassword().getBytes());
        if (resetPasswordDTO.getOldPassword() == null || resetOldPassword.equals(oldPassword)) {
            throw new PasswordErrorException("原密码有误！");
        }
        Member member = new Member();
        member.setMemberId(resetPasswordDTO.getMemberId());
        // 加密
        String resetNewPassword = DigestUtils.md5DigestAsHex(resetPasswordDTO.getNewPassword().getBytes());
        member.setPassword(resetNewPassword);
        member.setLastModifiedTime(LocalDateTime.now());
        memberMapper.update(member);
    }

    /**
     * 注册
     * @param memberRegisterDTO
     * @return
     */
    @Override
    public void register(MemberRegisterDTO memberRegisterDTO) {
        Member existingMember = memberMapper.selectByUsername(memberRegisterDTO.getUsername());

        if (existingMember != null) {
            throw new UsernameAlreadyExistsException("用户名已存在！");
        }

        Member member = new Member();
        BeanUtils.copyProperties(memberRegisterDTO, member);
        member.setPassword(DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
        member.setRegistrationTime(LocalDateTime.now());
        member.setMemberType("普通用户");

        // 插入新用户
        memberMapper.insert(member);
    }


    @Override
    public PageResult page(MemberPageQueryDTO memberPageQueryDTO) {
        PageHelper.startPage(memberPageQueryDTO.getPage(), memberPageQueryDTO.getPageSize());
        Page<Member> page = memberMapper.pageQuery(memberPageQueryDTO);
        long total = page.getTotal();
        List<Member> records = page.getResult();
        return new PageResult(total, records);
    }
}
